package com.chang.dp.services.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.dp.entity.BookSectionEntity;
import com.chang.dp.entity.EbookEntity;
import com.chang.dp.mappers.EbookMapper;
import com.chang.dp.services.EbookService;
import com.chang.dp.utils.EpubUtil;
import lombok.extern.slf4j.Slf4j;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.epub.EpubReader;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@Slf4j
public class EbookServiceImpl extends ServiceImpl<EbookMapper, EbookEntity> implements EbookService {
    @Value("${system.upload-path}")
    private String uploadPath;

    @javax.annotation.Resource
    BookSectionServiceImpl bookSectionServiceImpl;

    @Override
    public void addSections(EbookEntity ebook) {
        String fileName = ebook.getFileName();
        if (StringUtils.endsWith(fileName, ".epub")) {
            // 用文件名新建个文件夹名
            String dirName = "epub_" + StringUtils.substringBeforeLast(fileName, ".");

            // 读取电子书
            try {
                Path filePath = Paths.get(uploadPath).resolve(ebook.getFileName()).normalize();
                EpubReader epubReader = new EpubReader();
                Book book = epubReader.readEpub(Files.newInputStream(filePath));

                List<Resource> resources = book.getContents();
                List<BookSectionEntity> collect = IntStream.range(0, resources.size()).mapToObj(i -> {
                    Resource resource = resources.get(i);
                    BookSectionEntity bookSection = new BookSectionEntity();
                    bookSection.setBookId(ebook.getId());

                    try {
                        String content = new String(resource.getData(), StandardCharsets.UTF_8);
                        bookSection.setContent(content);
                        bookSection.setPageNumber(i + 1);
                        Document document = EpubUtil.getDocument(content);
                        bookSection.setTitle(EpubUtil.getTitle(document));
                        bookSection.setSubject(EpubUtil.getSubject(document));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    return bookSection;
                }).collect(Collectors.toList());

                // 保存图片
                for (Resource resource : resources) {
                    String imageName = resource.getHref();

                    if (StringUtils.endsWith(imageName, ".jpg")) {

                        String saveImageDir = uploadPath + "/" + dirName + "/";
                        String imagePath = saveImageDir + imageName;
                        try {
                            String content = new String(resource.getData(), StandardCharsets.UTF_8);
                            Document document = Jsoup.parse(content);
                            String imageSrc = document.select("img").attr("src");
                            EpubUtil.saveImage(book.getResources().getByHref(imageSrc).getInputStream(), imagePath, imageName);
                        } catch (IOException e) {
                            log.error("读取失败 ---> " + e.getMessage());
                        }
                    }
                }

                bookSectionServiceImpl.saveBatch(collect);
            } catch (IOException e) {
                log.error("读取失败 ---> " + e.getMessage());
            }
        }
    }

    private Book getBook(EbookEntity ebook) {

        return null;
    }

    @Override
    public boolean analyze(Long id) {
        EbookEntity ebook = this.getById(id);
        if (ebook.getAnalyzed() == 0) {
            this.addSections(ebook);
        }
        return true;
    }
}
